//
// Created by Tiany on 2021/6/21.
//字符串的顺序表表示

#include <stdlib.h>
#include <stdio.h>
#include "SeqString.h"

//创建空顺序串
PSeqString createNullStr_seq(int m) {
    PSeqString pSeqString = (PSeqString) malloc(sizeof(struct SeqString));
    if (pSeqString != NULL) {
        pSeqString->c = malloc(sizeof(char) * m);
        if (pSeqString->c) {
            pSeqString->MAXNUM = m;
            pSeqString->n = 0;
            return pSeqString;
        } else free(pSeqString);
    }
    printf("数据错误，请核查输入");
    return NULL;
}

//求字符串的子串
PSeqString subStr_seq(PSeqString pSeqString, int i, int j) {
    /*从字符串的第i个字符截取j长度的字符串*/
    PSeqString pSeqString1;
    int k;
    pSeqString1 = createNullStr_seq(j);
    if (pSeqString1 == NULL)return NULL;
    if (i > 0 && j > 0 && i < pSeqString->n) {
        if (pSeqString->n < i + j - 1)/*如果长度达不到j，则有几个截取几个*/
            j = pSeqString1->n - i + 1;
        for (k = 0; k < j; ++k) {
            pSeqString1->c[k] = pSeqString->c[i + k - 1];
        }
        pSeqString1->n = j;
    }
    return pSeqString1;
}

//将字符串写入顺序表
void writeStr_seq(PSeqString pSeqString, char s[], int length) {
    if (length > pSeqString->MAXNUM) {
        printf("顺序表长度不够！");
    }
    for (int i = 0; i < length; ++i) {
        pSeqString->c[i] = s[i];
        pSeqString->n++;
    }

}

//获取字符长度
int getLength(char s[]){
    int count=0;int i=0;
    while (s[i]!='\0'){
        count++;
        i++;
    }
    return count;
}

//读取并打印顺序表
void readString_seq(PSeqString pSeqString) {
    if (pSeqString != NULL) {
        printf("当前表长为：%d 表中元素为：", pSeqString->n);
        for (int i = 0; i < pSeqString->n; ++i) {
            printf("%c  ", pSeqString->c[i]);
        }
    }

}